import React from 'react';
import './registrationFeeManage.less';
import {browserHistory} from 'react-router';
import { Button, Table, Modal, Pagination, Form, message,Input,Select} from 'antd';
import $ from 'jquery';
import config from '../../../config/config';
const allRouter=config.router;
const Option = Select.Option;
const InputGroup = Input.Group;
const token = sessionStorage.getItem('token');
class RegistrationFeeManage extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            justDoctorList:[],//医生列表
            registrationFeeList:[],//挂号费列表
            allList:[],//作为分页时使用
            Inkey: undefined,// 关键字
            pagesize: 10,// 每页显示的页数
            pageindex: 1,// 当前页
            doctorSelected:undefined,//下拉框选择的医生
        }
    }
    componentDidMount() {
        //获取医生挂号费列表
        this.getAllRegistrationList();
    }
    //获取角色为医生的员工列表
    getAllRegistrationList() {
        //console.log(1);
        let url=allRouter.patientOrigin+'/doctor/list';
        $.ajax({
            url:url,
            type: "get",
            async: true,
            headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
            success:data=>{
                // console.log(data);
                if(data.code===200){
                    //给列表每一项增加索引
                    let doctorList=[];
                    if (data.users.length > 0) {
                        data.users.forEach((ele, i) => {
                            ele.index= i + 1;
                            if(ele.role==='医生'){
                                doctorList.push(ele);
                            }
                        });
                    }
                    // console.log(data);
                    this.setState({
                        justDoctorList:doctorList
                    },()=>{
                        //console.log(this.state.justDoctorList);
                        this.getDepartmentsList();
                    })
                }else{
                    console.log("获取员工列表出错");
                }
            },
            error:err=>{
                console.log(err);
            }
        })
    }
    //获取医生挂号费列表
    getDepartmentsList() {
        let url=allRouter.patientOrigin+'/registration/list';
        $.ajax({
            url:url,
            type: "get",
            async: true,
            headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
            success:data1=>{
                console.log('获取医生挂号费列表');
                console.log(data1);
                if(data1.code===200){
                    //给列表每一项增加索引
                    let registrationFeeList=[];
                    let userList=this.state.justDoctorList;
                   console.log(userList);
                    //把返回的用户列表和挂号费列表整合在一起，成为表格所需要的数据
                    if(data1.data){
                        if (data1.data.length > 0) {
                            data1.data.forEach((ele, i) => {
                                ele.index= i + 1;
                                if(userList.length>0){
                                    userList.map(item1=>{ //item1用户列表
                                        if(item1._id===ele.doctorid){
                                            registrationFeeList.push({department:item1.department[0].name,index:i+1,name:ele.doctorname,phone:item1.phone,id:ele._id,shop:item1.shop,fee:ele.price,level:ele.level,positionAttr:item1.post,state:ele.state})
                                        }
                                    })
                                }
                            });
                        }
                    }
                    this.setState({
                        registrationFeeList:registrationFeeList,
                        allList:registrationFeeList
                    },()=>{
                         console.log('------');
                         console.log(this.state.registrationFeeList);
                    })
                }else{
                    console.log("获取医生挂号费列表出错");
                }
            },
            error:err=>{
                console.log(err);
            }
        })
    }

    //分页
    changePage(pageindex) {
        this.setState({
            pageindex
        });
    }
    //删除医生挂号费数据
    deleteDepartment(recode) {
        let confirmString=<span style={{color:'red'}}>谨慎操作！删除之后医生挂号费为零。</span>;
        Modal.confirm({
            title: '删除医生挂号费',
            content: confirmString,
            onCancel:()=>{},
            onOk: () => {
                let url=allRouter.patientOrigin+'/registration/delete';
                $.ajax({
                    url:url,
                    type: "POST",
                    async: true,
                    headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
                    data:{
                        id:recode.id
                    },
                    success:data=>{
                        if(data.code===200){
                            message.success('删除成功！', 2);
                            this.getDepartmentsList();
                        }else{
                            message.info('删除失败');
                        }
                    },
                    error:err=>{
                        console.log(err);
                    }
                });
            }
        })
    }
    //编辑医生挂号费状态
    changeRegistratinFeeState(recode){
        //真正修改医生挂号费状态
        let that=this;
        let actualUpdateState=()=>{
            let url=allRouter.patientOrigin+'/registration/update';
            $.ajax({
                url:url,
                type: "POST",
                async: true,
                headers: { Authorization: 'Bearer '+sessionStorage.getItem('token')},
                data:{
                    id:recode.id,
                    state:currentState,
                },
                success:data=>{
                    if(data.code===200){
                        that.getDepartmentsList();
                    }else{
                        message.info('更改状态错误');
                    }
                },
                error:err=>{
                    console.log(err);
                }
            });
        };

        let currentState=recode.state;
        if(currentState==="启用"){
            currentState="禁用";
            let confirmString=<span style={{color:'red'}}>谨慎操作！禁用之后医生挂号费为零。</span>;
            Modal.confirm({
                title: '禁用医生挂号费',
                content: confirmString,
                onCancel:()=>{},
                onOk: () => {
                    actualUpdateState();
                }
            })
        }else if(currentState==="禁用"){
            currentState="启用";
            actualUpdateState();
        }
    }
    //搜索关键字
    changeInkey(e) {
        this.setState({
            Inkey: e.target.value
        })
    }
    //搜索
    searchRoles(e) {
        let value = e.target.value || this.state.Inkey;
       // console.log(value);
        let registrationFeeList = [];
        let registrationFeeList1 = [];
        this.state.allList.forEach(item=>{
            if(value){
                if(item.name.includes(value)||item.phone.includes(value)){
                    registrationFeeList1.push(item);
                }
            }else{
                registrationFeeList1.push(item);
            }
        });
        if(this.state.doctorSelected!=="allRole"){
            registrationFeeList1.forEach(item=>{
                //console.log(item.role);
                if(this.state.doctorSelected){
                    if(item.name===this.state.doctorSelected){
                        registrationFeeList.push(item);
                    }
                }else{
                    registrationFeeList.push(item);
                }
            });
        }else{
            registrationFeeList=registrationFeeList1;
        }
        registrationFeeList.sort((a,b)=>a.index-b.index);
        this.setState({registrationFeeList});
    }
    //选择医生的时候的搜索
    handleChangeRole(value){
        this.setState({
            doctorSelected:value,
        });
        let doctorList1 = [];
        if(this.state.Inkey){
            this.state.allList.forEach(item=>{
                if(item.name.includes(this.state.Inkey)||item.phone.includes(this.state.Inkey)){
                    doctorList1.push(item);
                }
            });
        }else{
            doctorList1=this.state.allList;
        }
        if(value==="allRole"){
            this.setState({
                registrationFeeList:doctorList1,
            });
            return;
        }
        //console.log(value);
        let registrationFeeList = [];
        doctorList1.forEach(item=>{
            //console.log(item.role);
            if(item.name===value){
                registrationFeeList.push(item);
            }
        });
        registrationFeeList.sort((a,b)=>a.index-b.index);
        this.setState({registrationFeeList});

    }

    render() {
        const columns = [
            {
                title: '序号',
                dataIndex: 'index',
                width: 50,
            },
            {
                title: '医生姓名',
                dataIndex: 'name',
                width: 100,
            }, {
                title: '手机号',
                dataIndex: 'phone',
                width: 100,
            }, {
                title: '所属科室',
                dataIndex: 'department',
                width: 100,
            }, {
                title: '所属诊所',
                dataIndex: 'shop',
                width: 200,
                render: text => <span>{text.length == 0 ? "——" : text.length == 1 ? text[0].name : text[0].name+'等'+text.length+'个诊所'}</span>
            }, {
                title: '挂号费',
                dataIndex: 'fee',
                width: 60
            }, {
                title: '医生称号',
                dataIndex: 'level',
                width: 80
            }, {
                title: '岗位属性',
                dataIndex: 'positionAttr',
                width: 80,
            }, {
                title: '状态',
                dataIndex: 'status',
                width: 50,
                render:(text,record)=>{ return <Button  type={record.state=='启用'?'primary':'danger'} onClick={this.changeRegistratinFeeState.bind(this,record)}>{record.state=='启用'?'已启用，点击禁用':'已禁用，点击启用'}</Button>}
            }, {
                title: '操作',
                width: 150,
                render: (text, record) => (
                    <div>
                        <Button onClick={()=>{browserHistory.push('addRegistrationFeeForm/'+record.id)}} type="primary" >编辑</Button>
                        <Button onClick={this.deleteDepartment.bind(this, record)}  type="danger">删除</Button>
                    </div>
                )
            }
        ];
        let index = this.state.pageindex;
        let size = this.state.pagesize;
        const data = this.state.registrationFeeList.slice(size*(index-1),size*index);
        return (
            <div className="container">
                <div className="store-manage-content">
                    <div className="my-clear-fix">
                        {/*增加按钮*/}
                        <div className="storeAdd employee-manage-add">
                            <Button onClick={() => { browserHistory.push('addRegistrationFeeForm/0') }}  type="primary"> <img src={require('../../../../images/add.png')} alt=""/>新增医生挂号费</Button>
                        </div>
                        <div className='role-manage-box-search my-clear-fix employee-manage-box-search'>
                            <div className='addetd-z employee-manage-search'>
                                <InputGroup compact>
                                    <Select  onChange={this.handleChangeRole.bind(this)} style={{width:'150px'}} placeholder="请选择医生">
                                        <Option value='allRole' >所有医生</Option>
                                        {this.state.justDoctorList.map(item=>{
                                            return (
                                                <Option value={item.name} key={item.name} >{item.name}</Option>
                                            )
                                        })}
                                    </Select>
                                    <Input
                                        placeholder="请输入姓名或手机号"
                                        value={this.state.Inkey}
                                        onChange={(e) => this.changeInkey(e)}
                                        onPressEnter={(e)=>this.searchRoles(e)}
                                    />
                                </InputGroup>
                            </div>
                            <div className="role-manage-right">
                                <Button type="primary" className='member-button' icon="search" onClick={this.searchRoles.bind(this)}>搜索</Button>
                            </div>
                        </div>
                    </div>
                    {/*医生挂号费列表 */}
                    <div className='all-roles-table'>
                        <Table
                            rowKey="id"
                            columns={columns}
                            dataSource={data}
                            pagination={false}
                            bordered
                        />
                    </div>
                    {/*分页*/}
                    <div className="pagination">
                        <Pagination current={this.state.pageindex} total={ this.state.registrationFeeList.length|| 1} defaultPageSize={this.state.pagesize} onChange={this.changePage.bind(this)} />
                    </div>
                </div>
            </div>
        )
    }
}
export default RegistrationFeeManage;